<template>
  <div class="workflow-create">
    <div class="header">
      <h2>创建工作流</h2>
      <el-button-group>
        <el-button @click="back">返回</el-button>
        <el-button type="primary" @click="importJson">导入JSON</el-button>
        <el-button type="primary" :loading="saving" @click="save">
          保存
        </el-button>
      </el-button-group>
    </div>

    <!-- 导入JSON对话框 -->
    <el-dialog
      v-model="importDialog.visible"
      title="导入工作流"
      width="80%"
      destroy-on-close
    >
      <div class="import-dialog">
        <el-upload
          class="json-uploader"
          drag
          accept=".json"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将 JSON 文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持导入 ComfyUI 导出的 JSON 工作流文件
            </div>
          </template>
        </el-upload>

        <div v-if="importDialog.content" class="preview-json">
          <h4>预览内容</h4>
          <el-input
            v-model="importDialog.content"
            type="textarea"
            :rows="10"
            readonly
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialog.visible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="!importDialog.content"
            @click="confirmImport"
          >
            确认导入
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="create-form"
    >
      <!-- 基本信息 -->
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>

        <el-form-item label="工作流名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入工作流名称" />
        </el-form-item>

        <el-form-item label="显示标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入显示标题" />
        </el-form-item>

        <el-form-item label="工作流描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入工作流描述"
          />
        </el-form-item>

        <el-form-item label="工作流类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择工作流类型">
            <el-option label="图像处理" value="image" />
            <el-option label="文本处理" value="text" />
          </el-select>
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="formData.tags"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入标签"
          >
            <el-option
              v-for="tag in tagOptions"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
      </el-card>

      <!-- 工作流配置 -->
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>工作流配置</span>
          </div>
        </template>

        <workflow-editor v-model="formData.workflow" />
      </el-card>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'
import WorkflowEditor from '@/components/WorkflowEditor.vue'

const router = useRouter()
const workflowStore = useWorkflowStore()

const formRef = ref<FormInstance>()
const saving = ref(false)

// 导入对话框
const importDialog = ref({
  visible: false,
  content: ''
})

// 打开导入对话框
const importJson = () => {
  importDialog.value.visible = true
}

// 处理文件选择
const handleFileChange = (file: File) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const content = e.target?.result as string
      // 验证是否为有效的 JSON
      JSON.parse(content)
      importDialog.value.content = content
    } catch (error) {
      ElMessage.error('无效的 JSON 文件')
    }
  }
  reader.readAsText(file.raw)
}

// 确认导入
const confirmImport = () => {
  try {
    formData.value.workflow = importDialog.value.content
    importDialog.value.visible = false
    ElMessage.success('导入成功')
  } catch (error) {
    ElMessage.error('导入失败')
  }
}

// 表单数据
const formData = ref({
  name: '',
  title: '',
  description: '',
  type: 'image',
  workflow: '{}',
  template: '{}',
  cover: '',
  tags: [] as string[],
  isPublic: false,
  serverIds: [] as string[],
  excludeServerIds: [] as string[]
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入工作流名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入显示标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择工作流类型', trigger: 'change' }
  ]
}

// 标签选项
const tagOptions = [
  '图像生成',
  '图像编辑',
  '风格迁移',
  '人像处理',
  '场景重建'
]

// 保存工作流
const save = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true

    await workflowStore.createWorkflow(formData.value)
    ElMessage.success('创建成功')
    router.push('/workflow')
  } catch (error: any) {
    console.error('Failed to create workflow:', error)
    ElMessage.error(error.message || '创建失败')
  } finally {
    saving.value = false
  }
}

// 返回列表
const back = () => {
  router.back()
}
</script>

<style scoped lang="scss">
.workflow-create {
  padding: 24px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h2 {
      margin: 0;
    }
  }

  .create-form {
    max-width: 800px;
    margin: 0 auto;

    .form-card {
      margin-bottom: 24px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }

  .import-dialog {
    .json-uploader {
      width: 100%;
      margin-bottom: 20px;
    }

    .preview-json {
      h4 {
        margin: 0 0 12px;
        color: #666;
      }
    }
  }
}
</style> 